#include <avr/io.h>
#include <util/delay.h>
#include "i2cbar.h"
#include "buzzer.h"


volatile uint8_t _buzzer_sound_nr;
volatile uint8_t _buzzer_delay;


// Periodendauer von c' bis h'
//255, 242, 228, 215, 203, 192, 181, 171, 161, 152, 144, 136
//128, 121, 114, 108, 102, 96, 91, 85, 81, 76, 72, 68
//64, 60, 57, 54, 51, 48, 45, 43, 40, 38, 36, 34


void buzzerSetup(void) {
	
		// set Buzzer to output
	CTRL_PORT_DDR |=  (1 << CTRL_BUZZER) ;
	
	
	
	// PWM initialisieren
    TCCR1A |= ( (0 << PWM1A) | (0 << PWM1B)
        | (0 << COM1A1) | (0 << COM1A0) | (1 << COM1B1) | (0 << COM1B0));
	TCCR1B |= ( ( 1 << CTC1 ) | (0 << CS13) | (1 << CS12) | (1 << CS11) | (1 << CS10) ); // 0000=off, 0001=clk, 0010=clk/2, ...
	//BUZZER_STOP();
		
	//_buzzer_sound_nr = 0;
	//_buzzer_delay = 0;
	
}



unsigned long buzzerLastMillis;


const uint8_t buzzerTone[] = {0, 114, 91, 76, 57, 20};

void buzzerLoop(void){

	if (_buzzer_sound_nr && _buzzer_sound_nr < 6) {
		BUZZER_PERIOD(buzzerTone[_buzzer_sound_nr]);
		BUZZER_PULSE(OCR1C >> 1);
		BUZZER_START();
		buzzerLastMillis = actualMillis;
		_buzzer_delay = 100;
		_buzzer_sound_nr = 0;

	}
	

	if(_buzzer_delay && (actualMillis - buzzerLastMillis > _buzzer_delay)) {
		_buzzer_delay = 0;
		BUZZER_STOP();
	}

	
}


